Rebinding and singleton-behaviour [NInject]

Posted by Maximilian Csuk on Stack Overflow See other posts from Stack Overflow or by Maximilian Csuk
Published on 2010-04-03T14:13:50Z Indexed on 2010/04/03 14:23 UTC
Read the original article Hit count: 412

Filed under:
|
|

Hi!

I have set up a NInject (using version 1.5) binding like this:

Bind<ISessionFactory>().ToMethod<ISessionFactory>(ctx => 
{
    try
    {
        // create session factory, might fail because of database issues like wrong connection string
    }
    catch (Exception e)
    {
        throw new DatabaseException(e);
    }
}).Using<SingletonBehavior>();

As you can see, this binding uses a singleton behavior but can also throw exception when something is not configured correctly, like a wrong connection string to the database.

Now, when the creation of a session factory fails at first (throwing a database exception), NInject doesn't try to create the object again but always returns null.

I would need NInject to check for null first and recreate when the instance is null, but of course not when there already is an instance successfully constructed (keeping it singleton). Like this:

var a = Kernel.Get<ISessionFactory>(); // might fail, a = null
// ... change some database settings
var b = Kernel.Get<ISessionFactory>(); // might not fail anymore, b = ISessionFactory object

Would I need to write a custom behavior or am I missing something else?

Thanks for your answers!

© Stack Overflow or respective owner

Related posts about ioc

Related posts about ninject